package com.gainloop.Api;

import java.util.ArrayList;

import org.alexd.jsonrpc.JSONRPCException;
import org.json.JSONException;

import com.gainloop.Api.Entity.Tag;
import com.gainloop.Api.Entity.Wish;

public class Tags extends ApiAbstract {
	
	public Tag getById(long id) throws JSONRPCException
	{
		try {
			ApiResponseObject<Tag> res =  new ApiResponseObject<Tag>(GetClient().callJSONObject("tags.getById", id), Tag.class);
			
			if(res.getReturnCode() != 0) {
				throw new ApiException("wrong usage: ", res);
			}
			
			return res.getData();
		} catch (JSONException e) {
			throw new ApiException("invalid respond");
		}
	}
	
	/**
	 * Find or create a new tag by name
	 * 
	 * @param name
	 * @return
	 * @throws JSONRPCException
	 */
	public Tag getByName(String name) throws JSONRPCException
	{
		try {
			ApiResponseObject<Tag> res = new ApiResponseObject<Tag>(GetClient().callJSONObject("tags.getByName", name), Tag.class);
			
			if(res.getReturnCode() != 0) {
				if(res.getReturnCode() == -1) {
					return null;
				}
				throw new ApiException("wrong usage: ", res);
			}
			
			return res.getData();
		} catch (JSONException e) {
			throw new ApiException("invalid respond");
		}
	}
	
	public ArrayList<Tag> getAllByWish(Wish wish) throws JSONRPCException
	{
		if(wish.getId() == 0) {
			throw new ApiException("wish id must be set");
		}

		try {
			ApiResponseArray<Tag> res = new ApiResponseArray<Tag>(GetClient().callJSONObject("tags.getAllByWishId", wish.getId()), Tag.class);
			
			if(res.getReturnCode() != 0) {
				throw new ApiException("wrong usage: ", res);
			}
			
			return res.getData();
		} catch (JSONException e) {
			throw new ApiException("invalid respond");
		}
	}
	
	public ArrayList<Tag> findTags(String tagPrefix) throws JSONRPCException
	{
		return findTags(tagPrefix, 10);
	}
	
	public ArrayList<Tag> findTags(String tagPrefix, int limit) throws JSONRPCException
	{
		if(tagPrefix.length() == 0) {
			throw new ApiException("tagPrefix must be set");
		}
		if(limit < 1) {
			throw new ApiException("limit must be positive");
		}
		if(limit > 30) {
			throw new ApiException("limit must be 30 maximum");
		}

		try {
			ApiResponseArray<Tag> res = new ApiResponseArray<Tag>(GetClient().callJSONObject("tags.findTags", tagPrefix), Tag.class);
			
			if(res.getReturnCode() != 0) {
				throw new ApiException("wrong usage: ", res);
			}
			
			return res.getData();
		} catch (JSONException e) {
			throw new ApiException("invalid respond");
		}
	}
	
}
